import { app } from "../../../scripts/app.js";

const { ComfyButton } = window.comfyAPI.button;

function insertYouTubeNode({ url, mode = "video", quality = "highest" }) {
    try {
        const graph = app.graph;
        const pos = app.canvas?.mouse ?? [100, 100];

        // Create the YouTube downloader node
        const ytNode = window.LiteGraph.createNode("YouTubeDownloader");
        ytNode.pos = Array.isArray(pos) ? pos : [100, 100];
        graph.add(ytNode);

        // Apply selected settings
        if (ytNode.widgets) {
            const setWidget = (name, value) => {
                const w = ytNode.widgets.find(w => w.name === name);
                if (w) w.value = value;
            };
            setWidget("url", url || "");
            setWidget("mode", mode);
            setWidget("quality", quality);
        }

        // Create a PreviewAny node and connect it to the downloader output
        try {
            const previewNode = window.LiteGraph.createNode("PreviewAny");
            // Place it to the right of the downloader node
            const offsetX = (ytNode.size?.[0] ?? 320) + 80;
            const offsetY = 0;
            previewNode.pos = [
                (ytNode.pos?.[0] ?? 100) + offsetX,
                (ytNode.pos?.[1] ?? 100) + offsetY,
            ];
            graph.add(previewNode);
            // Connect output 0 (file_path STRING) -> input 0 (source ANY)
            ytNode.connect?.(0, previewNode, 0);
        } catch (connectErr) {
            console.warn("Could not auto-create/connect PreviewAny node", connectErr);
        }

        graph.setDirtyCanvas(true, true);
    } catch (e) {
        console.error("Failed to insert YouTube node", e);
    }
}

async function promptAndInsertNode() {
    const url = window.prompt("YouTube URL to download:", "");
    if (!url) return;

    const mode = window.prompt("Mode: video | audio | subtitles", "video") || "video";
    let quality = "highest";
    if (mode === "video") {
        quality = window.prompt("Quality: highest | 144p | 360p | 720p", "highest") || "highest";
    }

    insertYouTubeNode({ url, mode, quality });
}

app.registerExtension({
    name: "ComfyUI.yt_dl.TopMenu",
    setup() {
        app.menu?.settingsGroup.append(
            new ComfyButton({
                icon: "download",
                tooltip: "Insert YouTube Download node",
                content: "YouTube DL",
                action: promptAndInsertNode,
            }),
        );
    },
});

